package com.jc.business.logisticscompany;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jc.common.util.HttpUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.jc.business.base.BaseBusiness;
import com.jc.common.util.MD5;
import com.jc.ds.model.LogisticsCompany;
import com.jc.framework.enums.ChannelSource;
import com.jc.service.h5.ShopService;
import com.jc.service.logisticscompany.LogisticsCompanyService;
import com.jc.service.model.h5.H5RespModel;



@Service
public class LogisticsCompanyBusiness extends BaseBusiness {
	
	@Value("${jingxi.h5.key}")
	private String key;
	@Value("${jingxi.h5.code}")
	private String code;
	@Value("${jingxi.h5.url}")
	private String baseUrl;

	
	
	@Autowired
	private ShopService shopService;
	
	@Autowired
	private LogisticsCompanyService logisticsCompanyService;
	
	/***
	 * 获取H5商城快递公司列表,定时获取，刷新本地的
	 */
	@Transactional
	public void getH5ChannelLogisticsCompanyList() throws IOException, URISyntaxException {
		long ts = new Date().getTime();
		Map<String,Object> body = new HashMap<String,Object>();
		body.put("code", code);
		body.put("encryptedString", MD5.passmd5("code="+code+"&ts="+String.valueOf(ts)+"&key="+key));
		body.put("ts",ts);

		String url = baseUrl + "order/logisticsCompany";
		System.out.println(url);
		//String ret = HttpUtil.postJson( url, JSONObject.toJSONString(body), null);
		String ret = HttpUtil.get( url, body);
		System.out.println(ret);

		if(StringUtils.isEmpty(ret)) {
			getLOGGER().error("调用H5商城获取物流公司列表错误");
		}
		Map map = JSONObject.parseObject(ret, Map.class);
		if(map.get("returnCode") != null && StringUtils.equals(map.get("returnCode").toString(), "0")) {
			//解析
			List<Object> logisticsList = JSONObject.parseObject(map.get("list").toString(),List.class);
			LogisticsCompany lc = null;
			for(Object o : logisticsList) {
				JSONObject jsonobject = JSONObject.parseObject(JSONObject.toJSONString(o));
				String id = jsonobject.getString("id");
				String name = jsonobject.getString("name");
				String code = jsonobject.getString("code");
				lc = new LogisticsCompany();
				lc.setName(name);
				if(CollectionUtils.isEmpty(logisticsCompanyService.queryAll(lc))) {
					lc.setChannelId(ChannelSource.APPV1.getName());
					lc.setCode(code);
					lc.setChannelLogisticsId(id);
					logisticsCompanyService.add(lc, false);
				}
			}
		}
		
		
		
		
		
		
		
		
		
		
	}
	

}
